<?php
/**
 * System dictionary class
 * @author Kirill A Egorov kirill.a.egorov@gmail.com 
 * @copyright Copyright (C) 2011-2012  Kirill A Egorov, 
 * DVelum project http://code.google.com/p/dvelum/ , http://dvelum.net
 * @license General Public License version 3
 */
class Dictionary
{
	static protected $_instances = array();
	protected function __construct(){}	
	protected function __clone(){}
	
	/**
	 * @var Config_Abstract
	 */
	protected $_data;	
	/**
	 * @return Dictionary
	 */
	static public function getInstance($name)
	{
		$name = strtolower($name);
		if(!array_key_exists($name,self::$_instances)){
			$obj =  new self();
			$obj->_data = Config::factory(Config::File_Array, Application::getConfig()->get('dictionary').$name.'.php');
			self::$_instances[$name] = $obj;
		}
		return self::$_instances[$name];
	}
	/**
	 * Check if key exists
	 * @param string $key
	 * @return boolean
	 */
	public function isValidKey($key){
		return $this->_data->offsetExists($key);
	}
	/**
	 * Get value by key
	 * @param string $key
	 * @return string
	 */
	public function getValue($key){
		return $this->_data->get($key);
	}
	/**
	 * Get all key - value pairs
	 * @return array
	 */
	public function getData(){
		return $this->_data->__toArray();
	}
	/**
	 * Add new key/value pair
	 * @param string $key
	 * @param string $value
	 * @return boolean
	 */
	public function addRecord($key , $value){
		return $this->_data->set($key, $value);
	}
	/**
	 * Remove record from dictionary
	 * @param string $key
	 * @return boolean
	 */
	public function removeRecord($key){
		return $this->_data->remove($key);
	}
	/**
	 * Save changes
	 * @return boolean
	 */
	public function saveChanges(){
		return $this->_data->save();
	}
	/**
	 * Return values as Javascrip array of objects
	 * @param boolean $addAll - defaults to false Add "all" value
	 * @return string
	 */
	public function __toJs($addAll = false){
	    $result = array();
	    if($addAll)
	        $result[] = array('id'=>'','title'=>Lang::getInstance()->ALL);
	    foreach ($this->_data as $k=>$v)
	        $result[] = array('id'=>$k,'title'=>$v);
	    return json_encode($result);    
	}
}